#include "lapackUtil.h"

#include "boost/foreach.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>
#include <iostream>
#include <string>

lapackUtil::lapackUtil(void)
{
}

lapackUtil::~lapackUtil(void)
{
}

int convertIJS2colMatrix(std::vector<unsigned int> II, std::vector<unsigned int> JJ, std::vector<double> SS, double* a, int m, int n) {
	if( (m*n<=0) ||
		(II.size() != JJ.size()) ||
		(JJ.size() != SS.size()) ||
		(a==NULL)
		)
		return -1;

	int i, j, pos;
	j=II.size();

	for(i=0; i<j; i++) {
		pos = (JJ[i] - 1) * m + II[i] - 1;
		a[pos] = SS[i];
	}

	return 0;
}

int convertVector2Array(std::vector<double> v, double* y) {
	double val;
	int i;
	
	i=0;
	BOOST_FOREACH(val, v ) {
		y[i]=val;
		++i;
	}

	return 0;
}

std::vector<double> readDoubleArray(const char* filename) {
	std::vector<double> result;

	std::ifstream ifs;
    std::string line;

    std::string s;
    std::vector<std::string> stvec;

	double x, y, z, val;

    ifs.open(filename);    

    if (ifs.is_open()) {
		std::getline(ifs, line);
		if (line.length()>0) {
			boost::algorithm::split(stvec, line, boost::algorithm::is_any_of(" \n"));

			BOOST_FOREACH(s, stvec) {
				try{
					val = boost::lexical_cast<double>(s);
					result.push_back(val);
				}
				catch(boost::bad_lexical_cast&) {
					printf("lexical_cast fail\n");
				}
			}
		}
    }

	return result;
}

bool writeDoubleArray(std::vector<double> param, const char* filename) {
	std::ofstream ofs;
	char buf[300];
	double val;
	std::string s;

	ofs.open(filename);
	BOOST_FOREACH(val, param) {
		sprintf(buf, "%2.14f ",val);
		s.clear();
		s.append(buf);

		ofs<<s;
	}

	ofs.close();

	return false;
}